<template>
  <page-header-wrapper :title="false">
    <a-card title="售后供应商详情">
      <template #extra> <a-button type="primary" @click="handleEdit()">编辑售后供应商</a-button></template>
      <a-descriptions bordered title="" size="small">
        <a-descriptions-item label="名称" :span="3"> {{ info?.name }} </a-descriptions-item>
        <a-descriptions-item label="初始余额" :span="3"> {{ info?.startAmount }}元 </a-descriptions-item>
        <a-descriptions-item label="状态" :span="3">
          <a-tag color="#82af6f" v-if="info?.status === '1'">合作中</a-tag>
          <a-tag color="#abbac3" v-else>停止合作</a-tag>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card title="往来账信息" style="margin-top: 24px">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="记账日期">
                <a-range-picker v-model="queryParam.date" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" @click="handleGroupCreate()">新增往来账</a-button>
        <!-- <a-button icon="cloud-upload">导出</a-button> -->
      </div>

      <a-table
        ref="table"
        size="default"
        :loading="loading"
        rowKey="key"
        :columns="columns"
        :data-source="loadData"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="types" slot-scope="text, record">
          <template>
            <div v-if="record?.types == 0">供应商回款</div>
            <div v-if="record?.types == 1">供应商退款</div>
            <div v-if="record?.types == 2">应收款</div>
            <div v-if="record?.types == 3">应退款</div>
            <div v-if="record?.types == 4">售后维修</div>
          </template>
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.status == 1">已审核</a-tag>
            <a-tag color="#abbac3" v-else>未审核</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <group-form
      ref="groupModal"
      :visible="groupVisible"
      :loading="groupLoading"
      :model="mdll"
      @cancel="handleGroupCancel"
      @ok="handleGroupOk"
    />
  </page-header-wrapper>
</template>

<script>
import CreateForm from './edit'
import GroupForm from './groupForm'
import moment from 'moment'
import { omit } from 'lodash-es'
import {
  addSvAcclogUsingPOST,
  getSvSuppliesUsingPOST,
  getSvAcclogListUsingGET,
  updateSvSuppliesUsingPOST,
} from '@/api/api/shouhouguanli.ts'
export default {
  name: 'ServiceSupplierDetail',
  components: {
    CreateForm,
    GroupForm,
  },
  data() {
    return {
      info: {},
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        date: [ moment().startOf('months').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD') ],
        status: '',
      },
      advanced: false,
      mdll: null,
      mdl: null,
      visible: false,
      groupVisible: false,
      groupLoading: false,
      value: '',
      confirmLoading: false,
      columns: [
        {
          title: '记账日期',
          dataIndex: 'date',
        },
        {
          title: '类型',
          dataIndex: 'types',
          needTotal: true,
          scopedSlots: { customRender: 'types' },
        },
        {
          title: '金额(元)',
          dataIndex: 'amount',
        },
        {
          title: '结余(元)',
          dataIndex: 'curAmount',
        },
        {
          title: '审核状态',
          dataIndex: 'status',
          needTotal: true,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '记账人',
          dataIndex: 'empName',
        },
        {
          title: '备注',
          dataIndex: 'memo',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
      loading: false,
      pagination: {},
    }
  },
  mounted() {
    this.getDetail()
    this.handleSearch(this.queryParam)
  },
  methods: {
    getDetail() {
      getSvSuppliesUsingPOST({ id: this.$route.params.id })
        .then((res) => {
          this.info = { ...res.data }
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleSearch(val) {
      this.loading = true
      const params = {
        ...val,
        svSupplyId: this.$route.params.id,
        startTime: val?.date?.[0] ? moment(val?.date?.[0]).format('YYYY-MM-DD') : null,
        endTime: val?.date?.[1] ? moment(val?.date?.[1]).format('YYYY-MM-DD') : null,
      }
      getSvAcclogListUsingGET({ ...omit(params, ['date']) })
        .then((res) => {
          this.loadData = res.data.list
          this.loading = false
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.loading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition:this.queryParam.queryCondition,
        status:this.queryParam.status,
        date:this.queryParam.date
      })
    },
    handleGroup() {
      this.groupVisible = true
    },
    handleEdit() {
      this.mdl = { ...this.info }
      this.visible = true
    },
    handleGroupCreate() {
      this.mdl = null
      this.groupVisible = true
    },
    handleDetail(record) {
      if(record?.types == 4){
        this.$router.push({ path: `/service/service/detail/${record.orderId}` })
      }else{
        this.$router.push({ path: `/service/supplier/order/${record?.orderId}` })
      }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 修改 e.g.
          updateSvSuppliesUsingPOST({ ...values, id: this.$route.params.id })
            .then(() => {
              this.handleSearch(this.queryParam)
              this.getDetail()
              this.$message.success('操作成功')
              this.visible = false
              this.confirmLoading = false
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleGroupOk() {
      const form = this.$refs.groupModal.form
      this.groupLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (!!values.id) {
            // 修改 e.g.
            const params = {
              ...values,
              accId:this.$route.params.id,
              date: values?.date,
            }
            updateSvSuppliesUsingPOST({ ...params })
              .then(() => {
                this.handleSearch(this.queryParam)
                this.$message.success('操作成功')
                this.groupVisible = false
                this.groupLoading = false
              })
              .catch((error) => {
                this.groupLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          } else {
            const params = {
              ...values,
              accId:this.$route.params.id,
              date: values?.date,
            }
            // 新增
            addSvAcclogUsingPOST({ ...params, })
              .then(() => {
                this.handleSearch(this.queryParam)
                this.$message.success('操作成功')
                this.groupVisible = false
                this.groupLoading = false
              })
              .catch((error) => {
                this.groupLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          }
        } else {
          this.groupLoading = false
        }
      })
    },
    handleGroupCancel() {
      this.groupVisible = false
      const form = this.$refs.groupModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
}
</script>
